package com.ruoyi.system.common;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.Assets;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.TAttachment;
import com.ruoyi.system.domain.THouseAssetsAttach;
import com.ruoyi.system.domain.TLandAssetsAttach;
import com.ruoyi.system.domain.TLeaseManageAttach;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cc
 * @date 2024年03月20日 9:42
 */
@Controller
@RequestMapping("/system/common")
public class systemCommonController extends BaseController {

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ITAttachmentService itAttachmentService;

    @Autowired
    private ITLeaseManageAttachService itLeaseManageAttachService;

    @Autowired
    private ITLandAssetsAttachService itLandAssetsAttachService;
    @Autowired
    private ITHouseAssetsAttachService itHouseAssetsAttachService;
    @Autowired
    private IAssetsService assetsService;
    @Autowired
    private ISysDictTypeService dictTypeService;

    @GetMapping("/uploads/{id}")
    public String uploads(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("parentId",id);
        return "common/upload";
    }

    @GetMapping("/houseUpload/{id}")
    public String houseUpload(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("parentId",id);
        return "common/houseUpload";
    }

    @GetMapping("/landUpload/{id}")
    public String landUpload(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("parentId",id);
        return "common/landUpload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file, TAttachment param) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            param.setId(IdUtils.randomNumber());
            param.setDelFlag(0);
            String originalFilename = file.getOriginalFilename();
            param.setName(originalFilename);
            param.setSize(file.getSize());
            int i = originalFilename.lastIndexOf(".");
            if (i > 0) {
                String extension = originalFilename.substring(i + 1);
                System.out.println("文件后缀名是：" + extension);
                param.setExt(extension);
            }
            param.setUrl(url);
            param.setCreateUserId(getUserId());
            itAttachmentService.insertTAttachment(param);
            TLeaseManageAttach leaseManageAttach = new TLeaseManageAttach();
            leaseManageAttach.setId(IdUtils.randomNumber());
            leaseManageAttach.setAttachId(param.getId());
            leaseManageAttach.setParentId(param.getParentId());
            leaseManageAttach.setDelFlag(0);
            leaseManageAttach.setCreateUserId(getUserId());
            leaseManageAttach.setType(Integer.valueOf(param.getType()));
            itLeaseManageAttachService.insertTLeaseManageAttach(leaseManageAttach);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/landUploads")
    @ResponseBody
    public AjaxResult landUploads(MultipartFile file, TAttachment param) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            param.setId(IdUtils.randomNumber());
            param.setDelFlag(0);
            String originalFilename = file.getOriginalFilename();
            param.setName(originalFilename);
            param.setSize(file.getSize());
            int i = originalFilename.lastIndexOf(".");
            if (i > 0) {
                String extension = originalFilename.substring(i + 1);
                System.out.println("文件后缀名是：" + extension);
                param.setExt(extension);
            }
            param.setUrl(url);
            param.setCreateUserId(getUserId());
            itAttachmentService.insertTAttachment(param);
            TLandAssetsAttach landAssetsAttach = new TLandAssetsAttach();
            landAssetsAttach.setId(IdUtils.randomNumber());
            landAssetsAttach.setAttachId(param.getId());
            landAssetsAttach.setParentId(param.getParentId());
            landAssetsAttach.setType(Integer.valueOf(param.getType()));
            landAssetsAttach.setDelFlag(0);
            landAssetsAttach.setCreateUserId(getUserId());
            itLandAssetsAttachService.insertTLandAssetsAttach(landAssetsAttach);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/houseUploads")
    @ResponseBody
    public AjaxResult houseUploads(MultipartFile file, TAttachment param) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            param.setId(IdUtils.randomNumber());
            param.setDelFlag(0);
            String originalFilename = file.getOriginalFilename();
            param.setName(originalFilename);
            param.setSize(file.getSize());
            int i = originalFilename.lastIndexOf(".");
            if (i > 0) {
                String extension = originalFilename.substring(i + 1);
                System.out.println("文件后缀名是：" + extension);
                param.setExt(extension);
            }
            param.setUrl(url);
            param.setCreateUserId(getUserId());
            itAttachmentService.insertTAttachment(param);
            THouseAssetsAttach houseAssetsAttach = new THouseAssetsAttach();
            houseAssetsAttach.setId(IdUtils.randomNumber());
            houseAssetsAttach.setAttachId(param.getId());
            houseAssetsAttach.setParentId(param.getParentId());
            houseAssetsAttach.setDelFlag(0);
            houseAssetsAttach.setCreateUserId(getUserId());
            houseAssetsAttach.setType(Integer.valueOf(param.getType()));
            itHouseAssetsAttachService.insertTHouseAssetsAttach(houseAssetsAttach);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     *  key（landhouse、所有资产，land、地产，house、房产，lease、租赁管理)
     */
    @GetMapping("/deptTreeData/{key}")
    @ResponseBody
    public List<Ztree> deptTreeData(@PathVariable("key") String key)
    {
        Assets assets = new Assets();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        if (key.equals("landhouse")){
            ztrees = assetsService.selectDeptTree(assets);
        } else if (key.equals("land")) {
            assets.setKey(key);
            ztrees = assetsService.selectDeptTreeland(assets);
        }else if (key.equals("house")) {
            assets.setKey(key);
            ztrees = assetsService.selectDeptTreehouse(assets);
        }
        return ztrees;
    }

    /*
   根据不同的deptId 查询不同的资产状态分类字典
    */
    @RequestMapping("/getDictData/{deptId}")
    @ResponseBody
    public TableDataInfo getDictData(@PathVariable("deptId") String deptId)
    {
        List<SysDictData> sysDictData = new ArrayList<>();
        Assets assets1 = assetsService.selectDeptById(Long.valueOf(deptId));
        String ancestors = assets1.getAncestors();
        String[] split = ancestors.split(",");
        if (split.length == 2){
            if (assets1.getDeptName().equals("土地资产")){
                sysDictData = dictTypeService.selectDictDataByType("land_state");
            }else {
                sysDictData = dictTypeService.selectDictDataByType("house_state");
            }
        } else if (split.length == 3) {
            String string = split[2];
            Assets assets2 = assetsService.selectDeptById(Long.valueOf(string));
            if (assets2.getDeptName().equals("土地资产")){
                sysDictData = dictTypeService.selectDictDataByType("land_state");
            }else {
                sysDictData = dictTypeService.selectDictDataByType("house_state");
            }
        }
        return getDataTable(sysDictData);
    }

    @PostMapping("/uploadsSyncData")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files, File param) throws Exception
    {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            List<File> list=new ArrayList<File>();
//            for (MultipartFile file : files)
//            {
//                // 上传并返回新文件名称
//                String fileName = FileUploadUtils.upload(filePath, file);
//                String url = serverConfig.getUrl() + fileName;
//                param.setFileurl(fileName);
//                param.setFilename(FileUtils.getName(fileName));
//                param.setCreateBy(getLoginName());
//                param.setOriName(file.getOriginalFilename());
//                param.setWebUrl(url);
//                list.add(param);
//                urls.add(url);
//                fileNames.add(fileName);
//                newFileNames.add(FileUtils.getName(fileName));
//                originalFilenames.add(file.getOriginalFilename());
//            }
//            fileService.insertFiles(list);
            AjaxResult ajax = AjaxResult.success();
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("coordinate")
    public String coordinatePage() {
        return "assets/map/coordinate";
    }

}
